package cn.sinata.wanglin.database;


import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;

public class CityDao {

	private DBMyHelper mDBHelper;
	private Context context;
	public CityDao(Context context){
		this.context=context;
		 mDBHelper=DBMyHelper.getInstance(context);
	}
	/**
	 * 判断表是否存在
	 * @param tableName table name
	 * @return 判断表是否存在
	 */
	public boolean tableIsExist(String tableName) {
		SQLiteDatabase db=mDBHelper.getWritableDatabase();
		if (db==null || !db.isOpen()) {
			return false;
		}
		boolean result = false;
		if (tableName == null) {
			return false;
		}
		Cursor cursor = null;
		try {
			String sql = "select count(*) as c from Sqlite_master  where type ='table' and name ='"
					+ tableName.trim() + "' ";
			cursor = db.rawQuery(sql, null);
			if (cursor.moveToNext()) {
				int count = cursor.getInt(0);
				if (count > 0) {
					result = true;
				}
			}

		} catch (Exception e) {
		}finally {
			if (cursor != null) {
				cursor.close();
			}
		}
		return result;
	}
	public List<CityInfo> getAllCityInfoByDB(int provinceid ,JavaListBeanCallBack<CityInfo> mCallBack){
		List<CityInfo> mCityInfos=new ArrayList<CityInfo>();
	    String table="city";
		if (tableIsExist(table)) {
			SQLiteDatabase db=mDBHelper.getWritableDatabase();
			if (db!=null && db.isOpen()) {
				Cursor cursor=db.rawQuery("select * from " + table+" where province_id = " +provinceid, null);
				while (cursor.moveToNext()) {
					int province_id = cursor.getInt(cursor.getColumnIndex("province_id"));
					int city_id = cursor.getInt(cursor.getColumnIndex("city_id"));
					String city_name=cursor.getString(cursor.getColumnIndex("city_name"));
					CityInfo mCityInfo=new CityInfo(city_name, city_id, province_id);
					
					mCityInfos.add(mCityInfo);
					
				}
				cursor.close();
				mCallBack.onresult(1, mCityInfos, "");
			}
		}

		return mCityInfos;
	}
	public List<List<CityInfo>> getAllCityInfoByDB2(final JavaListBeanCallBack<List<CityInfo>> mCallBack){
		ProvinceDao mProvinceDao=new ProvinceDao(context);
		final List<List<CityInfo>> mCityInfoss = new ArrayList<>();
		mProvinceDao.getAllProvinceInfoByDB(new JavaListBeanCallBack<ProvinceInfo>() {
			@Override
			public void onresult(int recode,final List<ProvinceInfo> data, String message) {
				if(data!=null){
					for (int i=0;i<data.size();i++){
						CityDao mCityDao=new CityDao(context);
						mCityDao.getAllCityInfoByDB(data.get(i).getProvince_id(), new JavaListBeanCallBack<CityInfo>() {
							@Override
							public void onresult(int recode, List<CityInfo> data, String message) {
								mCityInfoss.add(data);
							}
						});
					}
					mCallBack.onresult(1,mCityInfoss,"");
				}
			}




		});

		return mCityInfoss;
	}

}
